﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Web;
using System.Web.SessionState;
namespace wwwroot.Manage.ashx
{
    /// <summary>
    /// message 的摘要说明
    /// </summary>
    public class message : IHttpHandler, IReadOnlySessionState
    {
        #region //可直接修改接口
        /// <summary>
        /// 提示窗口，提示信息的汉字个数，太长自动截取
        /// </summary>
        private int MsgDisplayLen = 14;
        /// <summary>
        /// 是否启用流程消息在OA中显示
        /// </summary>
        private bool ShowFlowSMSInOA
        {
            get
            {
                string showFlowSMSInOA = BP.Sys.SystemConfig.AppSettings["ShowFlowSMSInOA"];
                //如果启用流程消息在OA中显示
                if (!string.IsNullOrEmpty(showFlowSMSInOA) && showFlowSMSInOA == "1")
                    return true;
                return false;
            }
        }
        #endregion
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string sql = "";
            //如果启用流程消息在OA中显示
            if (ShowFlowSMSInOA)
            {
                sql = string.Format(" select MyPK OID,Sender FK_UserNo,SendTo FK_SendToUserNo,RDT AddTime,EmailTitle Doc,"
                                    + "'' AttachFile,'审批' SubjectTitle,'/WF/App/EasyUI/EmpWorks.aspx?SMSta=1' GroupRedirect,'' GroupRedirectFormat,"
                                    + "'/WF/App/EasyUI/EmpWorks.aspx?SMSta=1' SingleRedirect,'' SingleRedirectFormat,EmailSta Received"
                                    + " from Sys_SMS where  SendTo='{0}' and EmailSta=0 and EmailTitle is not null "
                                    + " union ", BP.Web.WebUser.No);
            }
            //获取OA中消息
            sql += String.Format("SELECT cast(OID as varchar),FK_UserNo,FK_SendToUserNo,AddTime,Doc,AttachFile,SubjectTitle,GroupRedirect,GroupRedirectFormat,SingleRedirect,SingleRedirectFormat,Received"
                       + " FROM OA_ShortMsg where FK_SendToUserNo='{0}' and Received=0 order by OID", BP.Web.WebUser.No);
            DataTable dt = BP.DA.DBAccess.RunSQLReturnTable(sql);
            if (dt == null || dt.Rows.Count == 0)
            {//空信息
                context.Response.Write("");
            }
            else if (dt.Rows.Count == 1)
            {//单条时显示，这种情况会很多
                DataRow dr = dt.Rows[0];
                context.Response.Write(String.Format("{2}|<a onclick=addTab('{2}','{4}','icon-data3') href='#'>{1}</a><hr/><div style='font-size:10px;'>&nbsp;{0}&nbsp;来自于&nbsp;{3}</div>"
                                       , String.Format("{0:yyyy年MM月dd日 HH:mm:ss}", Convert.ToDateTime(dr["AddTime"]))
                                       , this.GetLimitedString(dr["Doc"], this.MsgDisplayLen)
                                       , dr["SubjectTitle"]
                                       , BP.OA.GPM.GetUserNames(Convert.ToString(dr["FK_UserNo"]))
                                       , dr["SingleRedirect"]));
            }
            else //多条时
            {                

                #region 形成dictSubject组
                //形成dictSubject组
                Dictionary<String, DataRow> dictSubject = new Dictionary<string, DataRow>();
                foreach (DataRow dr in dt.Rows)
                {
                    string key = Convert.ToString(dr["SubjectTitle"]);
                    if (!dictSubject.ContainsKey(key))
                        dictSubject.Add(key, dr);
                }
                string title = null;
                if (dictSubject.Count == 1)
                {
                    foreach (String key in dictSubject.Keys)
                    {
                        title = key;
                    }
                }
                else
                    title = "我的消息";
                #endregion 形成dictSubject组 结束

                string list = String.Empty;
                foreach (DataRow dr in dictSubject.Values)
                {
                    string s_href = null;
                    string s_text = null;
                    string s_title = null;
                    DataRow[] s_drs = dt.Select(String.Format("SubjectTitle='{0}'", dr["SubjectTitle"]));
                    DataRow s_dr = s_drs[0];
                    string s_singleRedirect = Convert.ToString(s_dr["SingleRedirect"]);
                    string s_subjectTitle = Convert.ToString(s_dr["SubjectTitle"]);
                    string s_groupRedirect = Convert.ToString(s_dr["GroupRedirect"]);
                    string s_doc = this.GetLimitedString(s_dr["Doc"], this.MsgDisplayLen);

                    if (s_drs.Length == 1)
                    {
                        s_href = s_singleRedirect;
                        s_title = s_subjectTitle;
                        s_text = String.Format("●{0}：{1}&nbsp;&nbsp;{2}来自于{3}"
                            , s_title
                            , s_doc
                            , BP.OA.Main.GetTimeEslapseStr(Convert.ToDateTime(dr["AddTime"]), null, null)
                            , BP.OA.GPM.GetUserNames(Convert.ToString(dr["FK_UserNo"])));
                    }
                    else
                    {
                        s_href = s_groupRedirect;
                        s_title = s_subjectTitle;
                        s_text = String.Format("●{2}：{0}{1}{2}", s_drs.Length, this.GetUnitStr(s_subjectTitle), s_subjectTitle);
                    }

                    if (!String.IsNullOrEmpty(list)) list += "<br/>";

                    if (s_title == "审批")//将审批的打开标签修改为待办，避免和左边的待办菜单打开不同标签
                        list += String.Format("<a onclick=addTab('{0}','{1}','icon-data3') href='#'>{2}</a>", "待办", s_href, s_text);
                    else
                        list += String.Format("<a onclick=addTab('{0}','{1}','icon-data3') href='#'>{2}</a>", s_title, s_href, s_text);
                }
                string bottomStat = String.Format("<hr/>共有{0}条短消息,请查收!", dt.Rows.Count);
                context.Response.Write(String.Format("{2}|{0}{1}", list, "", title));
            }
        }
        private string GetLimitedString(object evalString, int limitCount)
        {
            string str = Convert.ToString(evalString);
            if (str.Length > limitCount)
                return str.Substring(0, limitCount) + "..";
            else
                return str;
        }
        private string GetUnitStr(string subjectTitle)
        {
            switch (subjectTitle)
            {
                case "公告": return "则";
                case "新闻": return "条";
                case "邮件": return "封";
                default: return "条";
            }
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}